//
//  HXDUserAccountViewModel.swift
//  weibo
//
//  Created by huxuedong on 15/12/8.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

//MVVM(Model-View-ViewModel)设计模式：View引用viewModel，viewModel引用Model(不可逆)

import UIKit

class HXDUserAccountViewModel: NSObject {
    
    //初始化模型
    var userAccount: HXDUserAccount?
    //归档解档路径
    var path: String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.data")
    var userLogin: Bool {
        return accessToken != nil
    }
    var accessToken: String? {
        //where相当于"&&"，当where两边都满足条件时if let才为真
        if let accessToken = userAccount?.access_token where !isExpires {
            return accessToken
        }
        return nil
    }
    var isExpires: Bool {
        guard let expiresDate = userAccount?.expiresDate else {
            return true
        }
        //OrderedAscending为升序排列，判断当前日期是否小于过期日期
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        return true
    }
    //单例对象
    static let shareInstance: HXDUserAccountViewModel = HXDUserAccountViewModel()
    //私有构造方法，只能通过单例创建对象，不能init对象
    private override init() {
        super.init()
        userAccount = loadUserAccount()
    }

}

extension HXDUserAccountViewModel {
    
    func saveUserAccount(account: HXDUserAccount) {
        //归档
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
    }
    
    func loadUserAccount() -> HXDUserAccount? {
        //根据归解档路径进行解档
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HXDUserAccount
        return result
    }
    
}

extension HXDUserAccountViewModel {
    
    //获取accessToken以及userInfo
    func loadAccessToken(code: String, complete: (isSuccessed: Bool) -> ()) {
        HXDNetworkTools.shareTools.loadAccessToken(code) { (response, error) -> () in
            if error != nil {
                complete(isSuccessed: false)
                return
            }
            //回调数据response是否为字典
            guard let dict = response as? [String: AnyObject] else {
                return
            }
            //字典转模型
            let account = HXDUserAccount(dict: dict)
            self.userAccount = account
            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complete)
        }
    }
    
    private func loadUserInfo(uid: String, accessToken: String, complete: (isSuccessed: Bool) -> ()) {
        HXDNetworkTools.shareTools.loadUserInfo(uid, accessToken: accessToken) { (response, error) -> () in
            if error != nil {
                complete(isSuccessed: false)
                return
            }
            guard let dict = response as? [String: AnyObject] else {
                return
            }
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            self.saveUserAccount(self.userAccount!)
            complete(isSuccessed: true)
        }
    }
}
